package com.fable.sp.core.template.freemarker;

import com.fable.sp.core.domain.WidgetInstance;
import com.fable.sp.core.widget.Preference;
import com.fable.sp.core.widget.WidgetRequest;
import freemarker.ext.beans.BeanModel;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.ext.beans.MapModel;
import freemarker.ext.servlet.AllHttpScopesHashModel;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * .
 *
 * @author stormning on 16/8/26.
 */
public class WidgetHttpScopesHashModel extends AllHttpScopesHashModel {

    public static String WIDGET_REQUEST_KEY = "WidgetRequest";
    public static String WIDGET_PREFERENCES_KEY = "preferences";
    public static String WIDGET_INSTANCE_KEY = "instance";
    private static BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_23).build();
    private WidgetRequest widgetRequest;

    /**
     * Creates a new instance of AllHttpScopesHashModel for handling a single
     * HTTP servlet request.
     *
     * @param wrapper the object wrapper to use
     * @param context the servlet context of the web application
     * @param request the HTTP servlet request being processed
     */
    public WidgetHttpScopesHashModel(ObjectWrapper wrapper, ServletContext context, HttpServletRequest request, Map<String, Object> extras) {
        super(wrapper, context, request);
        if (extras != null) {
            widgetRequest = (WidgetRequest) extras.get(WIDGET_REQUEST_KEY);
            if (widgetRequest != null) {
                Map<String, Preference> preferences = widgetRequest.getPreferences();
                if (preferences != null) {
                }
                putUnlistedModel(WIDGET_PREFERENCES_KEY, new MapModel(preferences, beansWrapper));
                WidgetInstance instance = widgetRequest.getWidgetInstance();
                if (instance != null) {
                    putUnlistedModel(WIDGET_INSTANCE_KEY, new BeanModel(instance, beansWrapper));
                }
            }
        }
    }

    @Override
    public TemplateModel get(String key) throws TemplateModelException {
        if (widgetRequest != null) {
            Object attribute = widgetRequest.getAttribute(key);
            if (attribute != null) {
                return wrap(attribute);
            }
        }
        return super.get(key);
    }
}
